package com.dynamic.mybatis.core.parser.field;

import com.dynamic.mybatis.core.enums.CommandType;
import com.dynamic.mybatis.core.metadata.DynamicMappedStatement;
import com.dynamic.mybatis.core.metadata.MappedStatementMetaField;
import com.dynamic.mybatis.core.mock.Mock;
import com.dynamic.mybatis.core.session.DynamicSqlSession;
import com.dynamic.mybatis.core.toolkit.BeanUtils;
import org.apache.ibatis.session.Configuration;
import org.dom4j.DocumentException;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @Description
 * @Author xs
 * @Date 2022/11/17 11:05
 */
public class DynamicMixedMappedStatementFieldParser extends DynamicMappedStatementFieldFormatter {


    public DynamicMixedMappedStatementFieldParser(DynamicSqlSession dynamicSqlSession) {
        super(dynamicSqlSession);
    }

    @Override
    public Configuration getConfiguration() {
        return this.configuration;
    }

    /**
     　* @Description: 获取动态SQL字段信息
     　*/
    public DynamicMappedStatement parseMappedStatementField(DynamicMappedStatement dms) throws DocumentException {
        if(dms == null){
            return  null;
        }
        if(dms.getCommandType() == CommandType.StandardCommand.SELECT){
            //获取数据库字段信息
            List<MappedStatementMetaField> databaseFields = getDataBaseFieldQueryMappedStatement(dynamicSqlSession,dms,null);
            byte[] serializeFields = BeanUtils.serialize(databaseFields);
            //组装请求字段信息
            MappedStatementMetaField parameterFields =  inputParameterFieldParser(BeanUtils.deserialize(serializeFields),dms,true);
            //组装结果字段信息
            MappedStatementMetaField resultFields =  outputParameterFieldParser(BeanUtils.deserialize(serializeFields),dms);

            dms.toBuilder().setInputParameter(parameterFields).setInputParameterMock(Mock.mock(dms.getInputParameter().get(0))).setOutputParameter(resultFields);
            return dms;
        }else {
            List<MappedStatementMetaField> databaseFields = new ArrayList<>(); // getDataBaseFieldUpdateMappedStatementField(dynamicSqlSession,dms);

            MappedStatementMetaField parameterFields =  inputParameterFieldParser(databaseFields,dms,false);
            Object parameter = Mock.mock(parameterFields);
            if(dms.isBatchExecute() && parameter instanceof Collection){
                parameter = ((Collection)parameter).iterator().next();
            }
            //数据库字段
            databaseFields =   getDataBaseFieldUpdateMappedStatementField(dynamicSqlSession,dms,parameter);
            //请求参数
            parameterFields =  inputParameterFieldParser(databaseFields,dms,true);
            //响应参数
            MappedStatementMetaField resultFields =  outputParameterFieldParser(dms);

            dms.toBuilder().setInputParameter(parameterFields).setInputParameterMock(Mock.mock(dms.getInputParameter().get(0))).setOutputParameter(resultFields);

            return  dms;
        }
    }

}